package cn.yiyuan.auth.service.impl;

import cn.yiyuan.auth.entity.EmpEntity;
import cn.yiyuan.auth.entity.ShopEmpEntity;
import cn.yiyuan.auth.entity.ShopEntity;
import cn.yiyuan.auth.entity.ShopOperateLogEntity;
import cn.yiyuan.auth.mapper.EmpMapper;
import cn.yiyuan.auth.mapper.ShopEmpMapper;
import cn.yiyuan.auth.mapper.ShopMapper;
import cn.yiyuan.auth.mapper.ShopOperateLogMapper;
import cn.yiyuan.auth.service.IShopService;
import cn.yiyuan.base.customCode.Assert;
import cn.yiyuan.base.config.exception.BusinessException;
import cn.yiyuan.base.customCode.ResponseCode;
import cn.yiyuan.base.service.impl.BaseServiceImpl;
import cn.yiyuan.base.until.BaiduAuditUtils;
import cn.yiyuan.base.until.Email;
import cn.yiyuan.base.until.ShopUntil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @user m
 * @project car_mall_system
 * @date 2023-12-28
 * @package cn.yiyuan.auth.service.impl
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<ShopEntity> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private ShopEmpMapper shopEmployeeMapper;

    @Autowired
    private ShopOperateLogMapper logMapper;

    @Autowired
    private Email email;



    @Override
    @Transactional
    public void settlement(ShopEntity shop) throws Exception {
        EmpEntity admin =  shop.getAdmin();
        // 1 参数校验
        validateParam(shop,admin);

        // 4 对店铺信息做自动审核,调三方接口
        // 要对哪些信息做审核??  文本审核(店铺名称  店铺地址)  图片审核(  店铺logo)
        List<String> texts = Arrays.asList(shop.getName(),shop.getAddress());
        List<String> imgs = Arrays.asList(shop.getLogo());
        // 调用百度审核接口做审核
        Map<String,Object> map = BaiduAuditUtils.censor(texts,imgs);
        Boolean success = (Boolean)map.get("success");
        String message = (String) map.get("message");
        ShopOperateLogEntity log1 = new ShopOperateLogEntity();
        if(success==true){
            // 5 如果审核通过,就修改店铺状态=待激活,添加操作日志,并发送激活邮件到店铺管理员

            shop.setState(ShopUntil.AUDIT_ACTIVEATED);

            log1.setOperateType(ShopUntil.ACTIVEATED_SUCCESS);
            log1.setNote("审核成功");
            email.email(admin.getEmail(),"恭喜你,店铺信息审核通过,请点击激活链接及时激活!<a href='http://localhost:8081/shop/active?id'>点击激活!</a>");
        }else{
            // 6 如果审核未通过,就修改店铺状态=审核驳回,并发送失败邮件到店铺管理员
            shop.setState(ShopUntil.AUDIT);
            //店铺
            log1.setOperateType(ShopUntil.AUDIT);
            log1.setNote("审核驳回!"+message);  // 审核驳回要知道原因
            email.email(admin.getEmail(),"抱歉,您填写的"+message+"有误，请点击链接重新填写!<a href='http://localhost:8081/shop/active'>点击激活!</a>");

        }

        // 2 保存店铺信息到数据库,状态=待审核
        shop.setRegisterTime(new Date());   // 设置注册时间为当前时间
//         shop.setState(ShopUntil.AUDIT);
        shopMapper.insert(shop);

        // 3 保存店铺管理员信息到数据库,并且将店铺管理员和店铺要产生关联关系
        // 思考?? 如果员工信息已经存在怎么办???
        // 方案一: 如果员工信息已存在,直接返回错误信息,提示"管理员已存在",让这个员工到店铺列表下直接去新增店铺
        // 方案二: 如果员工信息已存在,就直接拿着这个已经存在的员工ID和店铺产生关联关系  采纳这种方案
        // 3.1 根据管理员的手机号查询员工信息
        EmpEntity adminByDb = empMapper.findByPhone(admin.getPhone());

        if(Objects.nonNull(adminByDb)){
            // 3.2 如果员工信息存在,直接将该员工信息和店铺产生关联关系,保存信息到t_org_shop_employee
            admin.setId(adminByDb.getId());
        }else{
            // 3.3 如果员工信息不存在,新增员工信息,再将新增后的员工和店铺产生关联关系,保存信息到t_org_shop_employee  待激活
            admin.setState(ShopUntil.AUDIT_ACTIVEATED);
            empMapper.insert(admin);
        }
        ShopEmpEntity shopEmployee = new ShopEmpEntity();
        shopEmployee.setShopId(shop.getId());
        shopEmployee.setEmployeeId(admin.getId());
        shopEmployee.setIsAdmin(1);
        shopEmployeeMapper.insert(shopEmployee);

        // 7 保存店铺的操作日志到数据库
        ShopOperateLogEntity log = new ShopOperateLogEntity();
        log.setShopId(shop.getId());
        log.setOperateType(ShopUntil.OPERATE_TYPE_REGISTER);
        log.setOperateId(0L); // 店铺入驻是用户来申请入驻的,并且用户无须登录,就可以申请店铺入驻
        log.setOperateTime(new Date());
        log.setNote("店铺"+shop.getName()+"申请入驻");
        logMapper.insert(log);

        // 添加店铺审核结果的操作日志
        log1.setShopId(shop.getId());
        log1.setOperateId(0L); // 操作人,自动审核,操作人可以为null或者是0L
        log1.setOperateTime(new Date());
        logMapper.insert(log1);

        if(success){
            shop.setState(ShopUntil.AUDIT_ACTIVEATED);
            // 审核通过,要发送激活邮件给店铺的管理员   自己完成的
        }else{
            // 审核不通过,要发送失败邮件给店铺的管理员   自己完成的
            shop.setState(ShopUntil.AUDIT);
           }
    }

    @Override
    public void updataactive(Long shopId) {

//        shopMapper.update();
    }

    private void validateParam(ShopEntity shop, EmpEntity admin) {
        // 1.1 对参数做非空校验,参数格式校验(先不做)
        if(Objects.isNull(shop) || Objects.isNull(admin) || StringUtils.isBlank(shop.getName()) ||
                StringUtils.isBlank(shop.getTel()) || StringUtils.isBlank(shop.getAddress()) ||
                StringUtils.isBlank(admin.getUsername()) || StringUtils.isBlank(admin.getEmail()) ||
                StringUtils.isBlank(admin.getPassword()) || StringUtils.isBlank(admin.getPhone())){
            // 抛出一个运行时异常,它会被controller的catch捕获到
            throw new BusinessException("店铺入驻信息输入不完整,请检查后重新提交!");
        }
        // 1.2 对两次密码做校验
//        if(!admin.getPassword().equals(admin.getPassword())){
//            throw new BusinessException("两次密码不一致,请检查后重新提交!");
//        }
        //断言工具判断
        Assert.isEq(admin.getPassword(),admin.getPassword(), ResponseCode.RESPONSE_CODE_4000);

        // 1.3 对店铺名称是否存在做校验
        // 1.3.1 根据店铺名称去t_org_shop表中查询
        ShopEntity shopByDb = shopMapper.findByName(shop.getName());
        // 1.3.2 判断对象不为空,说明店铺名称存在,就要返回错误信息
//        if(Objects.nonNull(shopByDb)){
//            throw new BusinessException("店铺名称已存在,请重新输入!");
//        }
        //使用断言工具
        Assert.isNull(shopByDb,ResponseCode.RESPONSE_CODE_1001);
    }
}
